//消息对象数组
let msgObjArr = new Array();

// 用于对话
let webSocket;
// 用于上传文件
let uploadWebSocket;

class Group {
    constructor() {
        if ("WebSocket" in window) {
            console.info("浏览器支持WebSocket");
        } else {
            // 浏览器不支持 WebSocket
            console.error("浏览器不支持WebSocket!");
        }
    }

    /**
     * 打开webSocket的连接
     */
    openWebSocket() {
        let username = $('#username').val();
        let groupId = $('#groupId').val();
        if ("" == username || null == username || undefined == username) {
            console.warn('参数username不能为空');
            return;
        }
        if ("" == groupId || null == groupId || undefined == groupId) {
            console.warn('参数groupId不能为空');
            return;
        }

        webSocket = new WebSocket(`ws://localhost:12101/im-end-web/ws/v1/group/${groupId}/${username}`, 'Authorization\'4f52f26643d647b9b6a4e94c1147f9c2');
        // webSocket = new WebSocket(`ws://192.168.80.109:12101/im-end-web/ws/v1/group/${groupId}/${username}`, 'Authorization\'4f52f26643d647b9b6a4e94c1147f9c2');
        let that = this;

        /**
         * 连通之后的回调事件
         */
        webSocket.onopen = function () {
            let username = $('#username').val();
            console.log(`${username}已经上线了`);
        };

        /**
         * 接收到消息的回调方法
         */
        webSocket.onmessage = function (event) {
            var messageJson = eval("(" + event.data + ")");
            console.info(`收到的来自服务端的消息是【${JSON.stringify(messageJson)}】`);
        };

        /**
         * 连接发生错误的回调方法
         */
        webSocket.onerror = function (e) {
            console.error("WebSocket连接发生错误");
        };

        /**
         * 连接关闭的回调方法
         */
        webSocket.onclose = function () {
            //alert("WebSocket连接关闭");
        }
    }

    /**
     * 向服务端发送消息
     */
    sendMessage() {
        var messageInput = $("#hz-message-input").html();
        var username = $("#username").val();
        let groupId = $('#groupId').val();
        // 发送消息
        webSocket.send(JSON.stringify({
            "groupId": groupId,
            "fromUserAccount": username,
            "content": messageInput,
            "type": 1
        }));
        $("#hz-message-body").append(
            "<div class=\"hz-message-list\">" +
            "<div class=\"hz-message-list-text right\">" +
            "<span>" + messageInput + "</span>" +
            "</div>" +
            "</div>");
        $("#hz-message-input").html("");
        //取出对象
        if (msgObjArr.length > 0) {
            var isExist = false;
            for (var i = 0; i < msgObjArr.length; i++) {
                var obj = msgObjArr[i];
                if (obj.toUserName == tarUserName) {
                    //保存最新数据
                    obj.message.push({ username: srcUserName, message: message, date: NowTime() });
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                //追加聊天对象
                msgObjArr.push({
                    toUserName: tarUserName,
                    message: [{ username: srcUserName, message: message, date: NowTime() }]//封装数据[{username:huanzi,message:"你好，我是欢子！",date:2018-04-29 22:48:00}]
                });
            }
        } else {
            //追加聊天对象
            msgObjArr.push({
                toUserName: tarUserName,
                message: [{ username: srcUserName, message: message, date: NowTime() }]//封装数据[{username:huanzi,message:"你好，我是欢子！",date:2018-04-29 22:48:00}]
            });
        }
    }

    /**
     * 直接关闭websocket的连接
     */
    closeWebSocket() {
        webSocket.close();
    }

    /**
     * 上传文件
     * @returns 
     */
    upload() {
        let username = $('#username').val();
        if ("" == username || null == username || undefined == username) {
            console.warn('参数username不能为空');
            return;
        }
        let groupId = $('#groupId').val();
        if ("" == groupId || null == groupId || undefined == groupId) {
            console.warn('参数groupId不能为空');
            return;
        }

        let filenameArray = $('#file').val().split('\\');
        let filename = filenameArray[filenameArray.length - 1];

        let type = 2;

        // if (null == uploadWebSocket || undefined == uploadWebSocket) {
//        uploadWebSocket = new WebSocket(`ws://localhost:17101/im-end-web/ws/v1/group/upload/${groupId}/${username}/${filename}/${type}`, 'Authorization\'4f52f26643d647b9b6a4e94c1147f9c2');
        uploadWebSocket = new WebSocket(`ws://localhost:15101/im-end-web-cluster/ws/v1/group/upload/${groupId}/${username}/${filename}/${type}`, 'Authorization\'4f52f26643d647b9b6a4e94c1147f9c2');
        // }

        /**
         * 连通之后的回调事件
         */
        uploadWebSocket.onopen = function () {
            let username = $('#username').val();
            console.log(`${username}已经上线了`);

            function uploadFile() {
                return new Promise(function (resolve, reject) {
                    let target = document.getElementById("file");
                    let reader = new FileReader();
                    reader.readAsArrayBuffer(target.files[0])
                    reader.onload = function () {
                        resolve(this.result);
                    };
                })
            };

            uploadFile().then(function (result) {
                uploadWebSocket.send(result);
            });
        };

        /**
         * 接收到消息的回调方法
         */
        uploadWebSocket.onmessage = function (event) {
            var messageJson = eval("(" + event.data + ")");
            console.info(`收到的来自服务端的消息是【${JSON.stringify(messageJson)}】`);
        };
    }
}



//将消息显示在对应聊天窗口    对于接收消息来说这里的toUserName就是来源用户，对于发送来说则相反
function setMessageInnerHTML(srcUserName, msgUserName, message) {
    //判断
    var childrens = $("#hz-group-body").children(".hz-group-list");
    var isExist = false;
    for (var i = 0; i < childrens.length; i++) {
        var text = $(childrens[i]).find(".hz-group-list-username").text();
        if (text == srcUserName) {
            isExist = true;
            break;
        }
    }
    if (!isExist) {
        //追加聊天对象
        msgObjArr.push({
            toUserName: srcUserName,
            message: [{ username: msgUserName, message: message, date: NowTime() }]//封装数据
        });
        $("#hz-group-body").append("<div class=\"hz-group-list\"><span class='hz-group-list-username'>" + srcUserName + "</span><span id=\"" + srcUserName + "-status\">[在线]</span><div id=\"hz-badge-" + srcUserName + "\" class='hz-badge'>0</div></div>");
    } else {
        //取出对象
        var isExist = false;
        for (var i = 0; i < msgObjArr.length; i++) {
            var obj = msgObjArr[i];
            if (obj.toUserName == srcUserName) {
                //保存最新数据
                obj.message.push({ username: msgUserName, message: message, date: NowTime() });
                isExist = true;
                break;
            }
        }
        if (!isExist) {
            //追加聊天对象
            msgObjArr.push({
                toUserName: srcUserName,
                message: [{ username: msgUserName, message: message, date: NowTime() }]//封装数据
            });
        }
    }

    // 对于接收消息来说这里的toUserName就是来源用户，对于发送来说则相反
    var username = $("#toUserName").text();

    //刚好打开的是对应的聊天页面
    if (srcUserName == username) {
        $("#hz-message-body").append(
            "<div class=\"hz-message-list\">" +
            "<p class='hz-message-list-username'>" + msgUserName + "：</p>" +
            "<div class=\"hz-message-list-text left\">" +
            "<span>" + message + "</span>" +
            "</div>" +
            "<div style=\" clear: both; \"></div>" +
            "</div>");
    } else {
        //小圆点++
        var conut = $("#hz-badge-" + srcUserName).text();
        $("#hz-badge-" + srcUserName).text(parseInt(conut) + 1);
        $("#hz-badge-" + srcUserName).css("opacity", "1");
    }
}

//监听点击用户
$("body").on("click", ".hz-group-list", function () {
    $(".hz-group-list").css("background-color", "");
    $(this).css("background-color", "whitesmoke");
    $("#toUserName").text($(this).find(".hz-group-list-username").text());

    //清空旧数据，从对象中取出并追加
    $("#hz-message-body").empty();
    $("#hz-badge-" + $("#toUserName").text()).text("0");
    $("#hz-badge-" + $("#toUserName").text()).css("opacity", "0");
    if (msgObjArr.length > 0) {
        for (var i = 0; i < msgObjArr.length; i++) {
            var obj = msgObjArr[i];
            if (obj.toUserName == $("#toUserName").text()) {
                //追加数据
                var messageArr = obj.message;
                if (messageArr.length > 0) {
                    for (var j = 0; j < messageArr.length; j++) {
                        var msgObj = messageArr[j];
                        var leftOrRight = "right";
                        var message = msgObj.message;
                        var msgUserName = msgObj.username;
                        var toUserName = $("#toUserName").text();

                        //当聊天窗口与msgUserName的人相同，文字在左边（对方/其他人），否则在右边（自己）
                        if (msgUserName == toUserName) {
                            leftOrRight = "left";
                        }

                        //但是如果点击的是自己，群聊的逻辑就不太一样了
                        if (username == toUserName && msgUserName != toUserName) {
                            leftOrRight = "left";
                        }

                        if (username == toUserName && msgUserName == toUserName) {
                            leftOrRight = "right";
                        }

                        var magUserName = leftOrRight == "left" ? "<p class='hz-message-list-username'>" + msgUserName + "：</p>" : "";

                        $("#hz-message-body").append(
                            "<div class=\"hz-message-list\">" +
                            magUserName +
                            "<div class=\"hz-message-list-text " + leftOrRight + "\">" +
                            "<span>" + message + "</span>" +
                            "</div>" +
                            "<div style=\" clear: both; \"></div>" +
                            "</div>");
                    }
                }
                break;
            }
        }
    }
});

//获取当前时间
function NowTime() {
    var time = new Date();
    var year = time.getFullYear();//获取年
    var month = time.getMonth() + 1;//或者月
    var day = time.getDate();//或者天
    var hour = time.getHours();//获取小时
    var minu = time.getMinutes();//获取分钟
    var second = time.getSeconds();//或者秒
    var data = year + "-";
    if (month < 10) {
        data += "0";
    }
    data += month + "-";
    if (day < 10) {
        data += "0"
    }
    data += day + " ";
    if (hour < 10) {
        data += "0"
    }
    data += hour + ":";
    if (minu < 10) {
        data += "0"
    }
    data += minu + ":";
    if (second < 10) {
        data += "0"
    }
    data += second;
    return data;
}

let group = new Group();

$(document).ready(function () {
    $("#openConnection").click(function () {
        group.openWebSocket();
    });

    $("#closeConnection").click(function () {
        group.closeWebSocket();
    });

    $("#sendMessage").click(function () {
        group.sendMessage();
    });

    $("#upload").click(function () {
        group.upload();
    });
});